<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\StudyLocationModel;
use App\Models\PageLinksModel;

class PageLink extends Controller
{
    public function index()
    {
        $pageLinksModel = new PageLinksModel();
        $studyLocationModel = new StudyLocationModel();

        // 获取 PageLinks 表和 StudyLocation 表关联查询的结果
        $builder = $pageLinksModel->builder();
        $builder->select('page_links.*, to_location.location_order as to_order, to_location.name as to_name, from_location.location_order as from_order,  from_location.name as from_name');
        $builder->join('study_location as to_location', 'page_links.to_page_id = to_location.id', 'left');
        $builder->join('study_location as from_location', 'page_links.from_page_id = from_location.id', 'left');
        $pageLinks = $builder->get()->getResultArray();

        return view('page_link_index', [
            'pageLinks' => $pageLinks
        ]);
    }

    public function exportCsv()
    {
        $pageLinksModel = new PageLinksModel();
        $studyLocationModel = new StudyLocationModel();

        // 获取 PageLinks 表和 StudyLocation 表关联查询的结果
        $builder = $pageLinksModel->builder();
        $builder->select('page_links.*, to_location.location_order as to_order, to_location.name as to_name, from_location.location_order as from_order,  from_location.name as from_name');
        $builder->join('study_location as to_location', 'page_links.to_page_id = to_location.id', 'left');
        $builder->join('study_location as from_location', 'page_links.from_page_id = from_location.id', 'left');
        $pageLinks = $builder->get()->getResultArray();

        // 设置 CSV 文件的表头
        $headers = [
            '序号',
            '起点基地名称',
            '起点基地序号',
            '终点基地序号',
            '终点基地名称',
            '终点基地得分',
            '设置时间'
        ];

        // 设置响应头
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="推荐链接数据列表.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');

        // 打开 PHP 输出流
        $output = fopen('php://output', 'w');

        // 写入 BOM 头以避免中文乱码
        fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));

        // 写入表头
        fputcsv($output, $headers);

        // 写入数据
        $index = 1;
        foreach ($pageLinks as $pageLink) {
            $row = [
                $index++,
                $pageLink['from_name'] ?? '',
                $pageLink['from_order'] ?? '',
                $pageLink['to_order'] ?? '',
                $pageLink['to_name'] ?? '',
                $pageLink['score'] ?? '',
                $pageLink['update_time'] ?? ''
            ];
            fputcsv($output, $row);
        }

        // 关闭输出流
        fclose($output);
    }
}